package com.jdew.thkj.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.BankCardBean;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.dialog.SingleChoiceDialog;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.ImageUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.view.CircleImageView;
import com.jdew.thkj.view.GlideCircleTransform;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;

import butterknife.Bind;
import cn.jpush.android.api.JPushInterface;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

/**
 * Created by yangzai on 2018/3/15 0015.
 */

public class ImproveActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.tv_bind)
    TextView tv_bind;
    @Bind(R.id.logo)
    CircleImageView logo;
    @Bind(R.id.logo_view)
    LinearLayout logo_view;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.view_nick)
    LinearLayout view_Nick;
    @Bind(R.id.zfb)
    TextView zfb;
    @Bind(R.id.view_zfb)
    LinearLayout view_Zfb;
    @Bind(R.id.weixin)
    TextView weixin;
    @Bind(R.id.view_weixin)
    LinearLayout view_modify;
    @Bind(R.id.view_modify)
    LinearLayout view_Weixin;
    @Bind(R.id.clickname)
    TextView clickname;
    @Bind(R.id.tv_wx_bind)
    TextView tv_wx_bind;
    @Bind(R.id.exit)
    TextView exit;
    @Bind(R.id.bank)
    TextView bank;
    @Bind(R.id.bank_bind)
    TextView bankBind;
    @Bind(R.id.view_bank)
    LinearLayout viewBank;
    private File tempFile;
    private String nickName;
    private String openId;
    private String AliAccount;
    private String iconUrl;
    private Bitmap bitmap;


    @Override
    public int bindLayout() {
        return R.layout.activity_improve;
    }

    @Override
    public void initView(View view) {
        back.setVisibility(View.VISIBLE);
        //创建拍照存储的临时文件
        createCameraTempFile(savedInstanceState);
        back.setOnClickListener(this);
        logo_view.setOnClickListener(this);
        view_Weixin.setOnClickListener(this);
        view_Zfb.setOnClickListener(this);
        view_Nick.setOnClickListener(this);
        view_modify.setOnClickListener(this);
        exit.setOnClickListener(this);
        viewBank.setOnClickListener(this);
        title.setText("完善资料");
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("tempFile", tempFile);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.logo_view: {
                singleDialog();
            }
            break;
            case R.id.view_zfb: {
                startActivity(new Intent(this, BindZhifuBaoActivity.class));
            }
            break;
            case R.id.view_bank: {
                startActivity(new Intent(this, BindBankActivity.class));
            }
            break;
            case R.id.view_nick: {
                Intent in = new Intent(ImproveActivity.this, CommonActivity.class);
                startActivityForResult(in, 1000);
            }
            break;
            case R.id.view_modify: {
                startActivity(new Intent(this, ModifyPassWordActivity.class));
            }
            break;
            case R.id.view_weixin: {
                commomDialog(0, "确定要绑定该手机登陆的微信号吗");
            }
            break;
            case R.id.exit: {
                commomDialog(1, "确定要退出程序吗");
            }
            break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        nickName = sp.getString("nickName", "");
        iconUrl = sp.getString("UserImgUrl", "");
        openId = sp.getString("UserWxId", "");
        AliAccount = sp.getString("AliAccount", "");
        if (!AliAccount.equals("")) {
            tv_bind.setText("已绑定");
            tv_bind.setTextColor(Color.BLACK);
            name.setText(nickName);
            clickname.setText(nickName);
        }
        if (!openId.equals("")) {
            tv_wx_bind.setText("已绑定");
            tv_wx_bind.setTextColor(Color.BLACK);
        }
        if (iconUrl.equals("")) {
            logo.setImageResource((R.mipmap.default_icon));
        } else {
            Glide.with(this).load(iconUrl).apply(bitmapTransform(new GlideCircleTransform(this))).into(logo);
        }
        QueryBankInfo();
    }

    public void singleDialog() {
        new SingleChoiceDialog.Builder(this).setTitle("提示")
                .addList("拍照")
                .addList("从系统相册中选取")
                .setOnItemClickListener(new SingleChoiceDialog.OnItemClickListener() {
                    @Override
                    public void OnItemClick(String title, int position) {
                        if (position == 1) {
                            autoObtainStoragePermission();
                        } else if (position == 0) {
                            autoObtainCameraPermission();
                        }
                    }
                }).show();
    }

    /**
     * 申请访问相机权限
     */
    private void autoObtainCameraPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {

                }
                requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, 104);
            } else {
                //有权限直接调用系统相机拍照
                gotoCarema();
            }
        }
    }

    /**
     * 动态申请sdcard读写权限
     */
    private void autoObtainStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 103);
            } else {
                gotoPhoto();
            }
        } else {
            gotoPhoto();
        }
    }

    /**
     * 到图库
     */
    private void gotoPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), 101);
    }

    /**
     * 跳转到照相机
     */
    private void gotoCarema() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        startActivityForResult(intent, 100);
    }

    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this, ClipImageActivity.class);
        intent.setData(uri);
        startActivityForResult(intent, 102);
    }

    /**
     * 创建调用系统照相机待存储的临时文件
     *
     * @param savedInstanceState
     */
    private void createCameraTempFile(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.containsKey("tempFile")) {
            tempFile = (File) savedInstanceState.getSerializable("tempFile");
        } else {
            tempFile = new File(checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"),
                    System.currentTimeMillis() + ".jpg");
        }
    }

    /**
     * 检查文件是否存在
     */
    private static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 104) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                gotoCarema();
            } else {
                // Permission Denied
            }
        } else if (requestCode == 103) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                gotoPhoto();
            } else {
                // Permission Denied
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 100: //调用系统相机返回
                if (resultCode == RESULT_OK) {
                    gotoClipActivity(Uri.fromFile(tempFile));
                }
                break;
            case 101:  //调用系统相册返回
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    gotoClipActivity(uri);
                }
                break;
            case 1000:
                if (resultCode == RESULT_OK) {
                    String nick = data.getStringExtra("nickName");
                    if (!"".equals(nick)) {
                        nickName = nick;
                        name.setText(nickName);
                        editor.putString("nickName", nick);
                        editor.apply();
                        clickname.setText(nickName);
                    }
                }
                break;
            case 102:  //剪切图片返回
                if (resultCode == RESULT_OK) {
                    final Uri uri = data.getData();
                    if (uri == null) {
                        return;
                    }
                    String cropImagePath = getRealFilePathFromUri(getApplicationContext(), uri);
                    bitmap = BitmapFactory.decodeFile(cropImagePath);
                    Glide.with(this).load(cropImagePath).apply(bitmapTransform(new GlideCircleTransform(this))).into(logo);
                    //接下来是上传到后台
                    UpLoadUserIcon(bitmap);
                }
                break;
            default:
                break;
        }
    }


    /**
     * 根据Uri返回文件绝对路径
     * 兼容了file:///开头的 和 content://开头的情况
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public String getRealFilePathFromUri(final Context context, final Uri uri) {
        if (null == uri) {
            return null;
        }
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    public void UpLoadUserIcon(Bitmap bitmap) {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("UserPhone", sp.getString("userPhone", ""));
        map.put("UserImgUrl", ImageUtils.Bitmap2StrByBase64(bitmap));
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).UploadAvatar(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + sp.getString("userPhone", "") + "UserImgUrl" + ImageUtils.Bitmap2StrByBase64(bitmap))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.getInstance(ImproveActivity.this).showMessage("上传头像异常");

            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    ToastUtils.getInstance(ImproveActivity.this).showMessage("上传用户头像成功");
                    loadIcon();
                } else if (json.get("code").equals("-1")) {
                    ToastUtils.getInstance(ImproveActivity.this).showMessage("上传用户头像失败");
                }
            }
        });
    }

    public void loadIcon() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).LoadAvatar(sp.getString("userPhone", ""), RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "Phone" + sp.getString("userPhone", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    String photoPath = json.getString("data");
                    editor.putString("UserImgUrl", photoPath);
                    editor.apply();
                    if (null == photoPath) {
                        return;
                    }
                    Glide.with(ImproveActivity.this).load(photoPath).apply(bitmapTransform(new GlideCircleTransform(ImproveActivity.this))).into(logo);
                }
            }
        });
    }

    public void QueryBankInfo() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetUserBankCardId(sp.getString("userPhone", ""), RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + sp.getString("userPhone", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<BankCardBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(BankCardBean bean) {
                if (bean.getCode().equals("0")) {
                    bankBind.setText("已绑定");
                    bankBind.setTextColor(Color.BLACK);
                    editor.putString("AffiliatedBank",bean.getData().getAffiliatedBank());
                    editor.putString("OpeningBank",bean.getData().getOpeningBank());
                    editor.putString("BankaCardId",bean.getData().getBankaCardId());
                    editor.apply();
                } else if (bean.getCode().equals("-1")) {
                    bankBind.setText("未绑定");
                }
            }
        });
    }

    public void commomDialog(final int type, String Message) {
        new CommonDialog.Builder(this)
                .setTitle("提示")
                .setMessage(Message)
                .setMessageGravity()
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (type == 1) {
                            editor.putString("userName", "");
                            editor.putString("token", "");
                            editor.putString("SpareTwo", "");
                            editor.putString("Alias", "");
                            editor.putString("userId", "");
                            editor.apply();
                            JPushInterface.deleteAlias(ImproveActivity.this, sp.getInt("sequence", 0));
                            startActivity(new Intent(ImproveActivity.this, LoginActivity.class));
                        } else {
                            IWXAPI mApi = WXAPIFactory.createWXAPI(ImproveActivity.this, AppConfig.APPID, true);
                            mApi.registerApp(AppConfig.APPID);
                            if (mApi != null && mApi.isWXAppInstalled()) {
                                EventBus.getDefault().post("changeIcon");
                                SendAuth.Req req = new SendAuth.Req();
                                req.scope = "snsapi_userinfo";
                                req.state = "wechat_sdk_demo";
                                mApi.sendReq(req);
                            } else {
                                ToastUtils.getInstance(ImproveActivity.this).showMessage("用户未安装微信");
                            }
                        }
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    public static final int getSequence() {
        int result = getYear();
        result = 31 * result + getMonth();
        result = 31 * result + getDay();
        return result;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != bitmap && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
            System.gc();
        }
    }

    /**
     * 获取当前年份
     *
     * @return
     */
    public static int getYear() {
        return Calendar.getInstance().get(Calendar.YEAR);
    }

    /**
     * 获取当前月份
     *
     * @return
     */
    public static int getMonth() {
        return Calendar.getInstance().get(Calendar.MONTH) + 1;
    }

    /**
     * 获取当前月份
     *
     * @return
     */
    public static int getDay() {
        return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    }
}
